package com.songcan.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.songcan.common.context.UserContext;
import com.songcan.common.vo.LogVO;
import com.songcan.gateway.exception.ValidatedExceotion;
import com.songcan.gateway.properties.HeaderProperties;
import com.songcan.gateway.utils.Base64Util;
import com.songcan.gateway.utils.ParamUtil;
import com.songcan.gateway.utils.ValidatedUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.songcan.gateway.contants.AuthUrls.*;
import static com.songcan.gateway.utils.GatewayContants.AUTH_LOGIN;
import static com.songcan.gateway.utils.GatewayContants.*;

@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {



    private  RedisTemplate redisTemplate;
    private HeaderProperties headerProperties;


    private static final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Autowired
    private AuthFilter(HeaderProperties headerProperties,RedisTemplate redisTemplate,ApplicationEventPublisher publisher){
        this.headerProperties = headerProperties;
        this.redisTemplate =redisTemplate;
    }

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        String path = serverHttpRequest.getPath().toString();

        if(!antPathMatcher.match("/**/login",path)&&!antPathMatcher.match("/**/refresh",path)){
            return chain.filter(exchange);
        }
        if(antPathMatcher.match("/**/login-out",path)){
            return chain.filter(exchange);
        }

        StringBuilder logBuilder = new StringBuilder();
        Map<String, String> codeParams = ParamUtil.parseRequest(exchange, logBuilder);



        String auth = "";
        String login = AUTH_LOGIN;
        //登录请求处理
        String uri = serverHttpRequest.getURI().toString();
        if (uri.contains(AUTH_LOGIN)) {
            MultiValueMap map = exchange.getRequest().getQueryParams();
            ValidatedUtil.imageValidated(map,codeParams,redisTemplate,"");
            //改写请求
            Map<String,String> manager = headerProperties.getManager();
            String keys = manager.get("clientId")+":"+manager.get("clientSercet");
            log.info("auth-header:,{}", keys);
             auth = AUTH_BASIC + Base64Util.getBase64(keys);
             login = AUTH_TOKEN+"?grant_type=password";
        }

        //刷新令牌
        if(uri.contains(AUTH_REFRESH)){
            //改写请求
            Map<String,String> manager = headerProperties.getManager();
            String keys = manager.get("clientId")+":"+manager.get("clientSercet");
            log.info("auth-header:,{}", keys);
            auth = AUTH_BASIC + Base64Util.getBase64(keys);
            login = AUTH_TOKEN+"?grant_type=refresh_token";
        }

        //三方登录
        if(uri.contains(THREE_LOGIN)){
            login = THREE_LOGIN;
            //改写请求
            String type = codeParams.get("type");
            if(StrUtil.isEmpty(type)){
                throw new ValidatedExceotion("类型不能为空");
            }
            ValidatedUtil.imageValidated(null,codeParams,redisTemplate,type);
            switch (type){
                case TYPE_MOBILE:{
                    Map<String,String> app = headerProperties.getApp();
                    String keys = app.get("clientId")+":"+app.get("clientSerct");
                    log.info("auth-header:,{}", keys);
                    auth = AUTH_BASIC + Base64Util.getBase64(keys);
                }
                break;
                case TYPE_WECHAT:{
                    Map<String,String> app = headerProperties.getWechat();
                    String keys = app.get("clientId")+":"+app.get("clientSerct");
                    log.info("auth-header:,{}", keys);
                    auth = "Basic " + Base64Util.getBase64(keys);
                }
                break;
                case TYPE_ALIYUN:{
                    Map<String,String> app = headerProperties.getAliyun();
                    String keys = app.get("clientId")+":"+app.get("clientSerct");
                    log.info("auth-header:,{}", keys);
                    auth = AUTH_BASIC + Base64Util.getBase64(keys);
                }
            }

        }

        ServerHttpRequest host = null;

        //重写http报文头部

        try {
            host = exchange.getRequest().mutate()
                    .headers(httpHeaders -> httpHeaders.remove("Content-Type"))
                    .header(AUTHORIZATION, auth)
                    .header("Content-Type", AUTH_CONTENT_TYPE)
                    .uri(new URI(login))
                    .build();

        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        exchange = exchange.mutate().request(host).build();


        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE+1;
    }


}


